<template>
	<view v-if="entity.userProjectId">
		<view class="nav-bar">
			<NavBar>
				<navigator open-type="navigateBack" hover-class="none" class="nav-back-view" slot="left">
					<image src="/static/nav-back-icon.png" class="nav-back"></image>
				</navigator>
				<view class="nav-back-view" slot="right">
					<view class="nav-back"></view>
				</view>

				<view slot="center" class="tabBar-view">
					<block v-if="projectType == '1'">
						<view class="tabBar-item" :class="{'tabBar-active': tabBarActive == 1}"
							@click="onTabBarEvent(1)">
							{{projectType == '1' ? '项目信息' : '交易信息'}}
						</view>
						<view class="tabBar-item" :class="{'tabBar-active': tabBarActive == 2}"
							@click="onTabBarEvent(2)">
							收益详情
						</view>
					</block>
					<view v-else class="tabBar-item" style="font-weight: 600;font-size: 33rpx;">预约信息</view>
				</view>
			</NavBar>
		</view>
		<view class="card-bg"></view>
		<block v-if="tabBarActive == 1">

			<view class="card-view">
				<view class="card-title">{{entity.projectName}}</view>
				<view class="card-tag">
					<view class="row">
						<block v-if="projectType == '1'">
							<view v-if="entity.preStatus == '10'" class="tag-item"
								style="--bg: linear-gradient(270deg, #FF764F 0%, #FF4127 100%)">
								存续中
							</view>
							<view v-else class="tag-item"
								style="--bg: linear-gradient(270deg, #7F504D 0%, #2C1101 100%);">
								已到期
							</view>
						</block>
						<view v-if="entity.type == '20'" class="tag-item"
							style="--bg: linear-gradient(270deg, #5860FF 0%, #2C32FF 100%)">
							线上购买
						</view>
						<view v-else class="tag-item" style="--bg: linear-gradient(270deg, #FFC456 0%, #FF912B 100%)">
							预约购买
						</view>
					</view>
					<block v-if="projectType == '2'">
						<view v-if="entity.status == '10'" class="state-view">
							<image src="/static/audit-pending.png" class="state-icon"></image>
							<view>审核中</view>
						</view>
						<view v-else-if="entity.status == '20'" class="state-view">
							<image src="/static/audit-succeed.png" class="state-icon"></image>
							<view style="color: #00C86C;">审核通过</view>
						</view>
						<view v-else-if="entity.status == '30'" class="state-view">
							<image src="/static/audit-err.png" class="state-icon"></image>
							<view style="color: #FF5A36;">审核失败</view>
						</view>
					</block>
				</view>

				<view class="card-content">
					<view class="num-view">
						<view class="num-item">
							<view class="num-text">{{entity.earningsRate}}%</view>
							<view class="num-desc">约定回报(年化)</view>
						</view>
						<view class="num-item">
							<view class="num-text">{{entity.subscriptionAmount}}</view>
							<view class="num-desc">出资金额(万元)</view>
						</view>
						<view class="num-item">
							<view class="num-text">{{entity.restrictName}}</view>
							<view class="num-desc">期限(月)</view>
						</view>
					</view>
					<view class="division"></view>
					<view class="cell-view">
						<view class="cell-item">
							<view class="label-view">交易日期：</view>
							<view class="value-view">{{dateFormat(entity.tradingTimes, 'YYYY.MM.DD')}}</view>
						</view>
						<!-- <view class="cell-item">
							<view class="label-view">审核日期：</view>
							<view class="value-view">{{dateFormat(entity.examineTimes, 'YYYY.MM.DD')}}</view>
						</view> -->
					</view>
					<view class="cell-item">
						<view class="label-view">主体类型：</view>
						<view class="value-view">{{entity.buyUserType == '20' ? '个人' : '企业'}}</view>
					</view>
					<view class="cell-view">
						<view class="cell-item">
							<view class="label-view">纸质协议：</view>
							<view class="value-view">{{entity.paperFlag == '10' ? '电子协议' : '纸质协议'}}</view>
						</view>
						<view class="cell-item">
							<view class="label-view">电子签名：</view>
							<view class="value-view">
								<view @click="onPreviewSign">查看</view>
								<view v-if="entity.signatureFlag == '10'" class="cell-but" @click="isDialog = true">重签
								</view>
							</view>
						</view>
					</view>
					<view class="cell-item" style="margin-top: 12upx;">
						<view class="label-view">生效日期：</view>
						<view class="value-view">{{dateFormat(entity.completeTimes, 'YYYY.MM.DD')}}</view>
					</view>
					<view class="cell-item">
						<view class="label-view">协议编号：</view>
						<view class="value-view">{{entity.agreementNumber}}</view>
					</view>
					<view v-if="projectType == '2' && entity.projectBank && entity.projectBank.projectAccountId"
						class="cell-item cell-bank">
						<view class="label-view">指定账户：</view>
						<view class="value-view">
							<view>{{entity.projectBank.accountName}} · {{entity.projectBank.bankNumber}}</view>
							<view>{{entity.projectBank.openBank}}</view>
						</view>
					</view>
					<view v-if="entity.userBank && entity.userBank.bankId" class="cell-item cell-bank">
						<view class="label-view">个人账户：</view>
						<view class="value-view">
							<view>{{entity.userBank.name}} · {{entity.userBank.bankNumber}}</view>
							<view>{{entity.userBank.bankBranch}}</view>
						</view>
					</view>
				</view>
			</view>

			<view v-if="projectType == '2' && entity.userAddress && entity.userAddress.addressId" class="address-view">
				<view class="address-label">联系地址：</view>
				<view class="address-content">
					<view style="width: 100%;">{{entity.userAddress.name}} · {{entity.userAddress.phone}}</view>
					<view style="width: 100%;">
						{{entity.userAddress.provinceName}}{{entity.userAddress.cityName}}{{entity.userAddress.areaName}}{{entity.userAddress.address}}
					</view>
				</view>
			</view>

			<view v-if="projectType == '2' && entity.status == '30'" class="desc-view">
				失败原因：{{entity.examineRemark || '-'}}
			</view>

			<FloatView v-if="entity.status == '20'">
				<view class="float-button">
					<view class="button-item" @click="onPreviewFile">预览协议</view>
					<view class="button-item button-active" @click="onDownloadFile">下载协议</view>
				</view>
			</FloatView>
		</block>

		<block v-else>

			<view class="earnings-view">
				<image src="/static/earnings-icon.png" class="earnings-icon"></image>
				<view class="earnings-top">
					<view class="earnings-num">{{queryData.totalIncome}}</view>
					<view class="earnings-desc">实际收益（元）</view>
				</view>
				<!-- <view class="earnings-cell">
					<view class="earnings-item">
						<view class="earnings-num">355555</view>
						<view class="earnings-desc">固定收益（元）</view>
					</view>
					<view class="earnings-item">
						<view class="earnings-num" style="color: #FF2615;">355555</view>
						<view class="earnings-desc">加息收益(元)</view>
					</view>
				</view> -->
			</view>
			<view class="earnings-list">
				<view class="list-title">
					<view>当前累计收益：</view>
					<view class="number-text">{{queryData.earningsDailyIncome}}</view>
					<view class="unit-text">元</view>
				</view>
				<view v-for="(item, index) in dataList" :key="index" class="list-item">
					<view class="label-view">
						<image src="/static/cell-time.png" class="label-icon"></image>
						<view>{{dateFormat(item.earningsTimes, 'YYYY.MM.DD')}}</view>
					</view>
					<view class="value-view">
						<view class="plus-sign">+</view>
						<view>{{item.amount}}</view>
					</view>
				</view>
				<Empty v-if="!dataList.length"></Empty>
			</view>
		</block>
		<view style="height: 260upx;"></view>
		<SignatureDialog v-if="isDialog" @confirm="onConfirm"></SignatureDialog>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isDialog: false,
				projectType: '1',
				tabBarActive: 1,
				userProjectId: '',
				entity: {
					userProjectId: "", // 主键ID
					projectId: "", // 项目ID
					userId: "", // 用户ID
					paperFlag: '', // 10电子协议 20纸质协议
					infoRestrictId: "", // 项目期限关联ID
					type: "", //  购买类型 10预约购买 20充值购买
					projectName: "", // 项目名称
					earningsRate: 0, // 预期收益率
					restrictName: "", // 项目期限
					agreementNumber: "", // 协议编号  电子或纸质
					signatureUrl: "", // 现用户签名URL
					subscriptionAmount: 0, // 认购金额 万元
					agreementUrl: "", // 协议URL
					tradingTimes: "", // 交易日期
					examineTimes: "", // 审核日期
					completeTimes: "", // 协议生效日期
					expireTimes: "", // 协议到期时间
					preStatus: "", // 项目运转状态 10存续中 20已到期
					initialInterestTimes: "", //  起息日期（审批选择）
					refundTimes: "", // 回款日期（审批选择）
					predictRefundTimes: "", // 预计回款日期（审批选择）
					status: "20", // 订单状态 10受理中 20交易成功 30交易失败
					examineRemark: null, // 审核状态描述
				},
				dataList: [],
				queryData: {
					pageNo: 1,
					pageSize: 20,
					total: 0,
					userProjectId: '',
					totalIncome: '',
					earningsDailyIncome: ''
				}
			}
		},
		onLoad(options) {
			this.projectType = options.projectType || '1'
			this.userProjectId = options.userProjectId
			this.queryData.userProjectId = options.userProjectId
			this.getProjectMyDetail()
		},
		onPullDownRefresh() {
			if (this.tabBarActive == 1) return this.getProjectMyDetail()
			this.queryData.pageNo = 1
			this.getProjectOrder()
		},
		onReachBottom() {
			if (this.tabBarActive == 1) return
			this.queryData.pageNo += 1
			this.getProjectOrder()
		},
		methods: {
			onTabBarEvent(event) {
				this.tabBarActive = event
				if (this.tabBarActive == 1) return
				this.queryData.pageNo = 1
				this.getProjectOrder()
			},
			async getProjectOrder() {
				uni.$util.showLoading()
				const res = await uni.$api.getProjectOrder(this.queryData).finally(uni.finally)
				const list = res.data.userProjectOrderEarnings.rows || []
				this.queryData.total = res.data.userProjectOrderEarnings.totalRows
				this.queryData.totalIncome = res.data.totalIncome
				this.queryData.earningsDailyIncome = res.data.earningsDailyIncome
				this.dataList = this.queryData.pageNo == 1 ? list : this.dataList.concat(list)
			},
			async onPreviewFile() {
				const system = uni.getSystemInfoSync()
				const fileUrl = this.IMG_URL + this.entity.agreementUrl
				if (system.platform == 'ios') {
					uni.$util.showLoading()
					const filePath = await uni.$util.downloadFile(fileUrl)
						.finally(uni
							.finally)
					return uni.openDocument({
						filePath: filePath
					});
				}
				if (system.platform == 'android') {
					const openFileModule = uni.requireNativePlugin("jushi-FilePreview")
					const [name, suffix] = this.entity.agreementUrl.split('.')
					openFileModule.openOnlineDocument({
						fileUrl: fileUrl,
						fileType: suffix,
						navTitle: this.entity.agreementUrl,
						navMode: 2 //1-禁用(不显示顶部导航栏)、2-固定显示在顶部(为默认值)、3-页面上滑隐藏，页面下滑显示
					})
				}
			},
			async onDownloadFile() {
				return
				const fileUrl = this.IMG_URL + this.entity.agreementUrl
				const filePath = await uni.$util.downloadFile(fileUrl)
				// return uni.saveFile({
				// 	tempFilePath:filePath,
				// 	success: (res) => {
				// 		console.log(res);
				// 	}
				// })
				let Path = plus.io.convertLocalFileSystemURL(filePath);
				console.log('Path----------', Path);
				plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, (fs) => {
					fs.root.getFile(Path, {
						create: true
					}, (fileEntry) => {
						console.log('fileEntry.fullPath', fileEntry.fullPath)
						fileEntry.file((file) => {
							let fileReader = new plus.io.FileReader();
							fileReader.readAsText(file);
							fileReader.onload = e => { //读文件成功
								console.log("读取文件成功");
								let txtData = e;
								console.log(txtData);
								this.createWriter(e)
							};
						})
					})
				}, function(e) {
					console.log('plus.io.-err', e);
				});
				// const filePath = await this.downloadFile(fileUrl)
				// console.log('filePath-', filePath);
				// plus.runtime.openFile(filePath)

			},
			createWriter(file) {
				plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, function(fs) {
					// 通过fs.root获取DirectoryEntry对象进行操作
					fs.root.getDirectory('/Library/Pandora/downloads', {
						create: true
					}, direEntry => {
						plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => {
							fs.root.getFile('/Library/Pandora/downloads/1777263234874839042.txt', {
								create: true
							}, fileEntry => {
								fileEntry.createWriter(writer => {
									writer.onwrite = e => {
										console.log("写入数据成功");
									}
									writer.write('写入数据成功');
								}, writerErr => {
									uni.showToast({
										title: '导出文件失败，请检查是否有权限',
										icon: 'none'
									});
								})
							})
						})
					})
				}, fsErr => {
					uni.showToast({
						title: '导出文件失败，请检查是否有权限',
						icon: 'none'
					});
				})
				// plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, (fs) => {
				// 	fs.root.getDirectory('/Library/Pandora/downloads/1777263234874839042.txt', {
				// 		create: true
				// 	}, fileEntry => {
				// 		console.log(fileEntry.fullPath)
				// 		plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, fs => {
				// 			fs.root.getFile(path, {
				// 				create: true
				// 			}, fileEntry => {

				// 			}, writerErr => {
				// 				resolve(500)
				// 				uni.showToast({
				// 					title: '导出文件失败，请检查是否有权限',
				// 					icon: 'none'
				// 				});
				// 			})
				// 		})
				// 		fileEntry.createWriter(writer => {
				// 			// 写入文件成功完成的回调函数  
				// 			writer.onwrite = e => {
				// 				console.log("写入数据成功");
				// 			};
				// 			// 写入数据  
				// 			writer.write('file.target.result');
				// 		})
				// 	})
				// 	// fs.root.getFile('/Library/Pandora/downloads/1777263234874839042.txt', {
				// 	// 	create: true // 文件不存在则创建  
				// 	// }, fileEntry => {
				// 	// 	// 文件在手机中的路径  
				// 	// 	console.log(fileEntry.fullPath)
				// 	// 	fileEntry.createWriter(writer => {
				// 	// 		// 写入文件成功完成的回调函数  
				// 	// 		writer.onwrite = e => {
				// 	// 			console.log("写入数据成功");
				// 	// 		};
				// 	// 		// 写入数据  
				// 	// 		writer.write('file.target.result');
				// 	// 	})
				// 	// }, e => {
				// 	// 	console.log("getFile failed: " + e.message);
				// 	// });
				// })
				// const fileUrl = this.IMG_URL + this.entity.agreementUrl
			},
			/**
			 * 获取详情
			 */
			async getProjectMyDetail() {
				uni.$util.showLoading()
				const res = await uni.$api.getProjectMyDetail(this.userProjectId).finally(uni.finally)
				this.entity = res.data
			},
			/**
			 * 签名回调 事件
			 */
			async onConfirm(event) {
				uni.$util.showLoading('上传中...')
				const res = await uni.$api.uploadFile(event).finally(uni.finally)
				uni.$util.showLoading('修改中...')
				await uni.$api.projectMyReSign({
					userProjectId: this.entity.userProjectId,
					signatureUrl: res.data.fileObjectName
				}).finally(uni.finally)
				this.isDialog = false
				this.getProjectMyDetail()
			},
			/**
			 * 预览签名
			 */
			onPreviewSign() {
				if (!this.entity.signatureUrl) return uni.$util.showToast('未获取到电子签名')
				uni.previewImage({
					current: 0,
					urls: [`${this.IMG_URL}${this.entity.signatureUrl}`]
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.nav-bar {
		position: sticky;
		top: 0;
		left: 0;
		z-index: 20;

		.nav-back-view {
			@extend .column;

			.nav-back {
				width: 43upx;
				height: 43upx;
			}
		}

		.tabBar-view {
			@extend .row;

			.tabBar-item {
				font-size: 25rpx;
				font-weight: 400;
				color: white;
				transition: all 0.3s;
				position: relative;
				@extend .column;

				&:before {
					content: "";
					width: 47rpx;
					height: 4px;
					position: absolute;
					bottom: -10upx;
					transition: all 0.3s;
				}
			}

			.tabBar-item+.tabBar-item {
				margin-left: 40upx;
			}

			.tabBar-active {
				font-size: 33rpx;
				font-weight: 600;

				&:before {
					background: white;
				}
			}
		}

	}

	.card-bg {
		width: 100%;
		height: 100upx;
		background: #FF2615;
	}

	.card-view {
		width: 707rpx;
		margin: 0 auto;
		background: #FFFFFF;
		border-radius: 14rpx;
		padding-top: 22upx;
		margin-top: -80upx;

		.card-title {
			width: 100%;
			padding: 0 30upx;
			font-size: 33rpx;
			font-weight: 500;
			color: #2C1101;
		}

		.card-tag {
			width: 100%;
			@extend .row-between;
			padding: 0 30upx;
			margin-top: 18upx;

			.state-view {
				@extend .row;
				font-weight: 400;
				font-size: 22rpx;
				color: #2C1101;

				.state-icon {
					width: 25upx;
					height: 25upx;
					margin-right: 11upx;
				}
			}

			.tag-item {
				padding: 5upx 11upx;
				font-size: 20rpx;
				font-weight: 400;
				color: #FFFFFF;
				background: var(--bg);
				border-radius: 4rpx;
			}

			.tag-item+.tag-item {
				margin-left: 11upx;
			}
		}

		.card-content {
			width: 670rpx;
			margin: 0 auto;
			position: relative;
			margin-top: 18upx;
			padding: 25upx 22upx;

			&:before {
				content: "";
				width: 100%;
				height: 250rpx;
				background: linear-gradient(180deg, #FFF6F4 0%, #FFFFFF 100%);
				border-radius: 7rpx;
				position: absolute;
				top: 0;
				left: 0;
				z-index: 1;
			}

			.num-view {
				width: 100%;
				position: relative;
				z-index: 2;
				@extend .row-between;

				.num-item {
					&:first-child {
						.num-text {
							color: #FF442F;
						}
					}

					.num-text {
						font-size: 40rpx;
						font-weight: 600;
						color: #2C1101;
					}

					.num-desc {
						font-size: 22rpx;
						font-weight: 400;
						color: #69442E;
					}
				}
			}

			.division {
				position: relative;
				z-index: 2;
				width: 100%;
				height: 1upx;
				margin-top: 25upx;
				margin-bottom: 11upx;
				background: #F7E8E4;
			}

			.cell-item {
				position: relative;
				z-index: 2;
				margin-top: 14upx;
				@extend .row-start;

				.label-view {
					font-size: 25rpx;
					font-weight: 400;
					color: #B8ACA3;
				}

				.value-view {
					font-size: 25rpx;
					font-weight: 400;
					color: #2C1101;
					@extend .row;

					.cell-but {
						padding: 5upx 18upx;
						@extend .row;
						border-radius: 7rpx;
						border: 1px solid #FF2615;
						font-size: 22rpx;
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						color: #FF2615;
						margin-left: 18upx;
					}
				}
			}

			.cell-bank {
				align-items: baseline;
				padding-top: 25upx;
				border-top: 1px solid #F7E8E4;

				.value-view {
					width: calc(100% - 125upx) !important;
					flex-direction: column;
					align-items: flex-start;
				}
			}

			.cell-view {
				width: 100%;
				@extend .row-between;
				align-items: flex-start;

				.cell-item {
					width: initial;
				}
			}
		}

	}

	.address-view {
		width: 707rpx;
		padding: 25upx 40upx;
		margin: 0 auto;
		margin-top: 18upx;
		background: #FFFFFF;
		border-radius: 14rpx;
		@extend .row-start;
		align-items: flex-start;

		.address-label {
			font-weight: 400;
			font-size: 25rpx;
			color: #B8ACA3;
		}

		.address-content {
			width: calc(100% - 125upx);
			font-weight: 400;
			font-size: 25rpx;
			color: #2C1101;
		}
	}

	.desc-view {
		width: 707rpx;
		padding: 25upx 40upx;
		margin: 0 auto;
		margin-top: 18upx;
		background: #FFF7F4;
		border-radius: 14rpx;
		font-weight: 400;
		font-size: 25rpx;
		color: #FF2615;
	}

	.float-button {
		width: 100%;
		padding: 0 22upx;
		@extend .row-between;

		.button-item {
			width: calc(100% / 2 - 9upx);
			height: 91rpx;
			border-radius: 45rpx;
			border: 1rpx solid #FF2615;
			@extend .column;
			font-size: 29rpx;
			font-weight: 500;
			color: #FF2615;
		}

		.button-active {
			background: linear-gradient(180deg, #FF7065 0%, #FF2615 100%);
			border-radius: 45rpx;
			color: #FFFFFF;
		}
	}



	.earnings-view {
		width: 707rpx;
		margin: 0 auto;
		background: #FFFFFF;
		border-radius: 14rpx;
		margin-top: -80upx;
		padding: 40upx;
		padding-bottom: 36upx;
		position: relative;

		.earnings-icon {
			width: 246upx;
			height: 203upx;
			position: absolute;
			right: 13upx;
			top: -31upx;
		}

		.earnings-top {
			.earnings-num {
				font-size: 47rpx;
				font-weight: 600;
				color: #FF442F;
			}

			.earnings-desc {
				font-size: 22rpx;
				font-weight: 400;
				color: #69442E;
			}
		}

		.earnings-cell {
			width: 100%;
			@extend .row-between;
			padding-top: 22upx;
			border-top: 1px solid #F7E8E4;
			margin-top: 40upx;

			.earnings-item {
				width: calc(100% / 2);

				.earnings-num {
					font-size: 40rpx;
					font-weight: 600;
					color: #2C1101;
				}

				.earnings-desc {
					font-size: 22rpx;
					font-weight: 400;
					color: #69442E;
				}
			}
		}
	}


	.earnings-list {
		width: 707rpx;
		margin: 0 auto;
		background: #FFFFFF;
		border-radius: 14rpx;
		margin-top: 18upx;
		padding: 0 40upx;
		padding-top: 25upx;

		.list-title {
			width: 100%;
			@extend .row-start;
			font-size: 25rpx;
			font-weight: 400;
			color: #69442E;
			align-items: baseline;
			margin-bottom: 25upx;

			.number-text {
				font-size: 33rpx;
				color: #FF2615;
			}

			.unit-text {
				font-size: 22rpx;
				margin-left: 10upx;
			}
		}

		.list-item {
			width: 100%;
			padding: 27upx 0;
			@extend .row-between;
			border-top: 1px solid #F7E8E4;

			.label-view {
				@extend .row;
				font-size: 25rpx;
				font-weight: 400;
				color: #69442E;

				.label-icon {
					width: 25upx;
					height: 25upx;
					margin-right: 13upx;
				}
			}

			.value-view {
				@extend .row;
				font-size: 29rpx;
				font-weight: 400;
				color: #FF2615;

				.plus-sign {
					margin-right: 10upx;
				}
			}
		}
	}
</style>